import webapp2
import jinja2
import os
import re

template_dir = os.path.join(os.path.dirname(__file__),'templates')
jinja_environment = jinja2.Environment(loader =jinja2.FileSystemLoader(template_dir),autoescape= True)


months = ['January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December']

month_abbvs = dict((m[:3].lower(),m) for m in months)


def valid_month(month):
    if month:
        mon = month[:3].lower()
        return month_abbvs.get(mon)
            
def valid_day(day):
    if day and day.isdigit():
        day = int(day)
        if day<31 and day>0:
            return day

def valid_year(year):
    if year and year.isdigit():
        y = int(year)
        if y >1900 and y < 2020:
            return year        
            
            
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
PASS_RE = re.compile(r"^.{3,20}$")
EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$") 

def valid_username(username):
    return USER_RE.match(username)
def valid_pass(password):
    return PASS_RE.match(password)
def valid_email(email):
    return EMAIL_RE.match(email)

form2="""
<html>
  <head>
    <title>Sign Up</title>
    <style type="text/css">
      .label {text-align: right}
      .error {color: red}
    </style>

  </head>

  <body>
    <h2>Signup</h2>
    <form method="post">
      <table>
        <tr>
          <td class="label">
            Username
          </td>
          <td>
            <input type="text" name="username" value="%(name)s">
          </td>
          <td class="error">
            %(error_name)s
          </td>
        </tr>

        <tr>
          <td class="label">
            Password
          </td>
          <td>
            <input type="password" name="password" value="">
          </td>
          <td class="error">
            %(error_pass)s
          </td>
        </tr>

        <tr>
          <td class="label">
            Verify Password
          </td>
          <td>
            <input type="password" name="verify" value="">
          </td>
          <td class="error">
          <td class="error">
            %(error_pass_verify)s
          </td>
          </td>
        </tr>

        <tr>
          <td class="label">
            Email (optional)
          </td>
          <td>
            <input type="text" name="email" value="%(email)s">
          </td>
          <td class="error">
             %(error_email)s           
          </td>
        </tr>
      </table>

      <input type="submit">
    </form>
  </body>

</html>
"""

form3= """
<html>
  <head>
    <title>Unit 2 Signup</title>
  </head>

  <body>
    <h2>Welcome, %(name)s!</h2>
  </body>
</html>
"""
            
form= """
<form method="post" >
    What is your birthday?
    <br>
    <label>
        month
        <input type = "text" name = "month" value = "%(month)s">
    </label>

    <label>
        day
        <input type = "text" name = "day" value = "%(day)s">
    </label>

    <label>
        year
        <input type = "text" name = "year" value = "%(year)s">
    </label>
    
    <div style="color: red">%(error)s</div>

    <br>
    <input type="submit" />
</form>
    """

class MainHandler(webapp2.RequestHandler):
    def write_form(self,error="",month="",day="",year=""):
        self.response.out.write(form % {"error": error,"month": month,"day": day,"year":year})
    def get(self):
        self.write_form()
    def post(self):
    
        month2 = self.request.get('month')
        user_month = valid_month(month2)
        user_day = valid_day(self.request.get('day'))
        user_year = valid_year(self.request.get('year'))
                        
        if not( user_month and user_day and user_year):
            self.write_form("dont",month2,user_day,user_year)
        else:
            self.response.out.write("Thanks")
        

class SignHandler(webapp2.RequestHandler):
    def write_form(self,name="",email="",error_name="",error_pass="",error_pass_verify="",error_email=""):
        self.response.out.write(form2 % {"name": name,"email": email,"error_name":error_name,"error_pass":error_pass,"error_pass_verify":error_pass_verify,"error_email":error_email})
    def get(self):
        self.write_form()
    def post(self):
        u_name = self.request.get("username")
        u_email = self.request.get("email")
        u_pass = self.request.get("password")
        u_pass_confirm = self.request.get("verify")
        
        u_name_check = valid_username(u_name)
        u_pass_check = valid_pass(u_pass)
        u_email_check = valid_email(u_email)    
        
        
        
        if u_name_check and u_pass_check and u_pass== u_pass_confirm and u_email =="":
            self.redirect("/welcome?name="+ u_name)
            #self.response.out.write(form3 %{"name":u_name})
            return
        
        if u_name_check and u_pass_check and u_email_check and u_pass== u_pass_confirm:
            self.redirect("/welcome?name="+ u_name)
            #self.response.out.write(form3 %{"name":u_name})
            return
        
        error_name = ""
        error_pass = ""
        error_verify = ""
        error_email =""
        if not u_name_check :
            error_name = "That's not a valid username."
        if not u_pass_check:
            error_pass = "That wasn't a valid password"
        else:
            if not u_pass == u_pass_confirm:
                error_verify = "Your passwords didn't match."
        if u_email_check==None and u_email!="":
            error_email = "That's not a valid email."
        
        self.write_form(u_name,u_email,error_name,error_pass,error_verify,error_email)

class WelcomeHandler(webapp2.RequestHandler):
    def write_form(self,u_name=""):
        self.response.out.write(form3 %{"name":u_name})
    
    def get(self):
        name = self.request.get("name")
        self.write_form(name)

        
app = webapp2.WSGIApplication([('/', MainHandler),('/signup', SignHandler),('/welcome', WelcomeHandler)],debug=True)
        
    

    
